/*

    This file is part of Hometree.

    Hometree is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Hometree is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Hometree.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2011,2012 Roman Held

*/

/*===========================================================================*\
**      Include Dateien
\*===========================================================================*/
#include <QDebug>
#include <QMessageBox>
#include <QStringList>
#include <QFile>
#include <QDir>
#include "treeitem.h"
#include "htr/htrglobal.h"

#define DIR_SEPARATOR "/"

/*===========================================================================*\
**      Implementation Klasse "TreeItem"
\*===========================================================================*/
/*!f---------------------------------------------------------------------------
*/
TreeItem::TreeItem(const TreeItemData &data, QObject *parent)
 : QObject(parent)
{
  mParentItem = NULL;
  mViewWidget = NULL;
  mData       = data;
  mState      = Collapsed;
  mAnimationTime = 0;
  initIcons();
}

/*!f---------------------------------------------------------------------------
*/
TreeItem::TreeItem(const TreeItemData &data, TreeItem *parent)
 : QObject(parent)
{
  mViewWidget = NULL;
  mParentItem = parent;
  mData       = data;
  mState      = Collapsed;
  mAnimationTime = 0;
  initIcons();
}

/*!f---------------------------------------------------------------------------
*/
TreeItem::TreeItem(const QString &dirName, TreeItem *parent)
 : QObject(parent)
{
  mViewWidget = NULL;
  mParentItem = parent;
  mData.name  = dirName;
  mData.text  = dirName;
  mData.itemType = NodeItem;
  mData.resourceType = Htr::InvalidType;
  mState      = Collapsed;
  mAnimationTime = 0;
  initIcons();
}

/*!f---------------------------------------------------------------------------
*/
TreeItem::TreeItem(TreeItem *parent)
 : QObject(parent)
{
  mViewWidget = NULL;
  mParentItem = parent;
  mData.name  = "";
  mData.itemType  = Invalid;
  mData.resourceType  = Htr::InvalidType;
  mState      = Collapsed;
  mAnimationTime = 0;
  initIcons();
}

/*!f---------------------------------------------------------------------------
*/
TreeItem::~TreeItem()
{
  deleteChildren();
}

/*!p---------------------------------------------------------------------------
*/
void TreeItem::initIcons()
{
    mExpIcon    = QIcon(QPixmap(":/images_tbvviews/folder_open.png"));
    mColIcon    = QIcon(QPixmap(":/images_tbvviews/folder_closed.png"));
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::appendChild(TreeItem *item)
{
  mChildItems.append(item);
  item->setParentItem(this);
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::removeChild(TreeItem *item)
{
  mChildItems.removeAll(item);
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::selfDestroy()
{
  if (mParentItem)
    mParentItem->removeChild(this);
  deleteLater();
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::serialize(QDataStream *stream) const
{
    Q_ASSERT(stream);
    (*stream) << type();
}

/*!f---------------------------------------------------------------------------
*/
QString TreeItem::path(const QString &childPath) const
{
    if (!mParentItem)
        return childPath;
    QString newName = name()+(childPath.isEmpty()?"":DIR_SEPARATOR+childPath);
    if (mParentItem && mParentItem->isRoot())
        return newName;
    return mParentItem->path(newName);
}

/*!f---------------------------------------------------------------------------
*/
TreeItem *TreeItem::child(int row)
{
  return mChildItems.value(row);
}

/*!f---------------------------------------------------------------------------
*/
TreeItem *TreeItem::takeChild(int index)
{
  Q_ASSERT(index < mChildItems.count());
  return mChildItems.takeAt(index);
}

/*!f---------------------------------------------------------------------------
*/
int TreeItem::childCount() const
{
  return mChildItems.count();
}

/*!f---------------------------------------------------------------------------
*/
int TreeItem::columnCount() const
{
  return COL_COUNT;
}

/*!f---------------------------------------------------------------------------
*/
QVariant TreeItem::data(int col) const
{
    switch (col) {
        case COL_NAME: return mData.text;
        case COL_TYPE: switch (mData.resourceType){
                         case Htr::MimeDataType : return "MimeData";
                         default  : return "";
                       };
	default:
		qWarning() << "TreeItem::data: unknown column" << col;
    }
    return QVariant();
}

/*!f---------------------------------------------------------------------------
*/
TreeItem *TreeItem::parent() const
{
  return mParentItem;
}

/*!f---------------------------------------------------------------------------
*/
TreeItem *TreeItem::childByPath(const QString &path) const
{
    QStringList pathArgs = path.split(DIR_SEPARATOR);
    return itemByPathParts(pathArgs);
}

/*!p---------------------------------------------------------------------------
*/
TreeItem *TreeItem::itemByPathParts(QStringList &pathParts) const
{
    if (pathParts.isEmpty())
        return const_cast<TreeItem*>(this);
    QString name = pathParts.takeFirst();
    TreeItem *item = childByName(name);
    if (item)
        return item->itemByPathParts(pathParts);
    return NULL;
}

/*!f---------------------------------------------------------------------------
*/
TreeItem *TreeItem::childByName(const QString &name) const
{
    foreach (TreeItem *item, mChildItems) {
        if (item->name()==name)
            return item;
    }
    return NULL;
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::deleteChildren()
{
  while(mChildItems.count())
    mChildItems.takeFirst()->deleteLater();
}

/*!f---------------------------------------------------------------------------
*/
int TreeItem::relativeRow() const
/*
  Relative Row: Row-Index des Parents:
*/
{
  if (mParentItem)
    return mParentItem->mChildItems.indexOf(const_cast<TreeItem*>(this));
  return 0;
}

/*!f---------------------------------------------------------------------------
*/
int TreeItem::absoluteRow() const
/*
  Absolute Row: Row-Index des Parents ab dem Root-Item:
*/
{
  TreeItem *parentItem = const_cast<TreeItem*>(this);
  Q_ASSERT(parentItem->parent());

  while (parentItem->parent()->parent())
    parentItem = parentItem->parent();

  TreeItem *rootItem  = parentItem->parent();
  return rootItem->mChildItems.indexOf(rootItem);
}

/*!f---------------------------------------------------------------------------
*/
QIcon TreeItem::icon() const
{
    if (type()==NodeItem)
        return (mState==Expanded?mExpIcon:mColIcon);
    return mData.icon;
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::deleteAction()
{
  /*
    int ret = QMessageBox::question(mViewWidget, "Views", "Wollen Sie die View "+path()+" wirklich loeschen?", QMessageBox::Yes, QMessageBox::No);
    if (ret==QMessageBox::No)
        return;

    TbDbConnection db;
    QString query = db.getQuery(303);
    db.prepare(query);
    db.addBindValue(path());
    db.transaction();
    if (!db.exec()) {
        qWarning() << "TreeItem::deleteAction(): Query" << query << "konnte nicht abgesetzt werden.";
        qWarning() << "Meldung:" << db.lastError().databaseText();
        return;
    }
    db.commit();
    TbLog::Instance()->writeLog("tbvviews",path(),"geloescht");
    emit deleted();
*/
}

/*!f---------------------------------------------------------------------------
*/
void TreeItem::animate()
{
  if (mAnimationTime <= 0)
    return;
  
  Q_ASSERT(mAnimationTime > 0);
  QColor newTextColor(mAnimationTime,0,255-mAnimationTime);
  mTextColor = newTextColor;
  emit changed(this);
  mAnimationTime -= 5;
}

/*!f---------------------------------------------------------------------------
*/
QString TreeItem::toolTip() const
{
    QString tip;
    QString row("<tr><td>%1</td><td>%2</td></tr>");
    tip = "<table>";
    tip += row.arg("Name:").arg(mData.name);
    tip += row.arg("Comment:").arg(mData.comment);
    tip += "</table>";
    return tip;
}
